package com.itzmn.newcode.offer1;

import java.util.ArrayList;

/**
 * @Author: 张梦楠
 * @Date: 2018/12/19 18:52
 * 简书：https://www.jianshu.com/u/d611be10d1a6
 * 码云：https://gitee.com/zhangqiye
 * @Description: 顺时针打印矩阵
 *
 *  输入一个矩阵，按照从外向里以顺时针的顺序依次打印出每一个数字，例如，
 *  如果输入如下4 X 4矩阵： 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
 *  则依次打印出数字1,2,3,4,8,12,16,15,14,13,9,5,6,7,11,10.
 *
 *
 *  1  2  3  4
 *  5  6  7  8
 *  9  10 11 12
 *  13 14 15 16
 *  17 18 19 20
 *  顺时针打印1,2,3,4,8,12,16,20,19,18,17,13,9,5,6,7,11,15,14,10
 *
 *  一共4行，4列
 *  默认0行0列
 *  1  2  3  4  5
 *  6  7  8  9  10
 *  11 12 13 14 15
 *
 */
public class _19_ClockwisePrintingMatrix {
    public static void main(String[] args) {
        new _19_ClockwisePrintingMatrix().test();
    }
    private void test() {

        int[][] arrs = {{1,2,3,4},{5,6,7,8},{9,10,11,12},{13,14,15,16},{17,18,19,20}};
        //int[][] arrs = {{1,2,3,4,5}};
        //int[][] arrs = {{1},{2},{3},{4},{5}};
        printMatrix(arrs);
    }
    public ArrayList<Integer> printMatrix(int [][] matrix) {
        ArrayList<Integer> integers = new ArrayList<>();
        int row = matrix.length;
        int col = matrix[0].length;
        int num = Math.min(row%2 == 0? row/2:row/2+1,col%2 == 0? col/2:col/2+1);
        System.out.println(num);

        for (int i=0;i<num;i++){

            // 行一定，列递增
            for (int ct=i;ct<col-i;ct++){
                System.out.print(matrix[i][ct]+" ");
                integers.add(matrix[i][ct]);
            }
            // 列一定，行递增
            for (int rr = i+1;rr<row-i;rr++){
                System.out.print(matrix[rr][col-i-1]+" ");
                integers.add(matrix[rr][col-i-1]);
            }


            if (row-1-i == i){
                break;
            }
            // 行一定，列递减
            for (int cb = col-i-2;cb>=i;cb--){
                System.out.print(matrix[row-i-1][cb]+" ");
                integers.add(matrix[row-i-1][cb]);
            }

            if (col-i-1 == i){
                break;
            }

            //列一定，行递减
            for (int rl = row-i-2;rl>i;rl--){
                System.out.print(matrix[rl][i]+" ");
                integers.add(matrix[rl][i]);
            }

            System.out.println();
        }

        return integers;
    }
}
